#include "recbox.h"
#include "ui_recbox.h"
#include <QJsonObject>
#include <cmath>
#include <QDebug>
RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);
    // recBox.cpp构造函数中添加如下代码 // 测试
    //    RecBoxItem* item = new RecBoxItem();
    //    ui->recListUpHLayout->addWidget(item);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if (row == 2) {
        this->row = 2;
        this->col = 8;
    }  else {
        ui->recListDown->hide();
    }

    // 图片保存起来
    imageList = data;

    // 默认显⽰第0组
    currentIndex = 0;

    // 计算总共有⼏组图⽚，ceil表⽰向上取整
    count = ceil(data.size() / col);

    // 在RevBox中添加图片
    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    // 溢出掉之前旧元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for (auto item : recUpList) {
        ui->recListUpHLayout->removeWidget(item);
        delete item;
    }

    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for (auto item : recDownList) {
        ui->recListDownHLayout->removeWidget(item);
        delete item;
    }

    // 注意坐标位置
    for(int i = currentIndex*col; i < col+currentIndex*col; i++){
        RecBoxItem* item = new RecBoxItem();

        // 设置音乐图片和对应文本
        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());

        // 将RecBoxItem对象添加到RecBox中 测试
        // ui->recListUpHLayout->addWidget(item);

        // recMusicBox：col为4，元素添加到ui->recListUpHLayout中
        // supplyMuscBox: col为8， ui->recListUpHLayout添加4个，ui->recListDownHLayout添加4个
        // 即supplyMuscBox上下两⾏都要添加
        // 如果是recMusicBox：row为1，只能执⾏else，所有4个RecBoxItem都添加到ui->recListUpHLayout中

        // 如果是supplyMuscBox：row为2，col为8，col/2结果为4，i为0 1 2 3时，元素添加到ui->recListDownHLayout中
        // i为4 5 6 7时，元素添加到ui->recListUpHLayout中

        if (i >= 4 + currentIndex*col) {
            ui->recListDownHLayout->addWidget(item);
        } else {
            ui->recListUpHLayout->addWidget(item);
        }

    }
}

void RecBox::on_upPage_clicked()
{
    // 点击btUp按钮，显⽰前4张图⽚，如果已经是第⼀张图⽚，循环从后往前显⽰
    currentIndex--;
    if (currentIndex < 0) {
        currentIndex = count - 1;
    }
    createRecBoxItem();
}

void RecBox::on_downPage_clicked()
{
    // 点击btUp按钮，显⽰前8张图⽚，如果已经是第⼀张图⽚，循环从后往前显⽰
    currentIndex++;
    if (currentIndex >= count) {
        currentIndex = 0;
    }

    createRecBoxItem();
}
